package app;

import static app.Constants.KEYS;
import static app.Constants.USER;

import java.io.IOException;
import java.security.KeyPair;
import java.security.PrivateKey;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import db.DBUser;
import db.DBUtils;

public class AppServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private String param(HttpServletRequest req, String param) {
        KeyPair keys = (KeyPair) req.getSession().getAttribute(KEYS);
        PrivateKey privateKey = keys.getPrivate();

        // FIXME FIXME param.decript()?!

        return req.getParameter(param);
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                    IOException {

        HttpSession session = request.getSession();

        String action = request.getParameter("action");

        if ("cadastroUsuario".equals(action)) {
            DBUser user = (DBUser) session.getAttribute(USER);

            if (user.isAdmin()) {

                String name = param(request, "name");
                String password = param(request, "password");
                String pis = param(request, "pis");
                boolean isAdmin = Boolean.valueOf(param(request, "isAdmin"));

                DBUtils.createUser(name, password, pis, isAdmin);

                response.getWriter().write("key=" + user.getKey());
            }
        } else if ("consultaUsuario".equals(action)) {
            String name = param(request, "name");
            for (DBUser user : DBUtils.getAllUsers()) {
                if (user.getName().equals(name)) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("name=").append(user.getName()).append(';');
                    sb.append("pis=").append(user.getPis()).append(';');
                    sb.append("key=").append(user.getKey()).append(';');

                    response.getWriter().write(sb.toString());
                    break;

                }
            }

        } else if ("".equals(action)) {
            // ..........
        }

        response.getWriter().close();

    }

}
